package com.uxwine.alarm.main;

import java.util.Calendar;

public class Alarm {
	private int id;
	private String name;
	private long time;
	private int cycle;
	private int sound;
	private boolean effective;	
	
	public Alarm()
	{
		id = 0;
		name = "alarm";
		time = 0;
		cycle = 0;
		effective = true;
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getTime() {
		return time;
	}
	public void setTime(long time) {
		this.time = time;
	}
	public int getCycle() {
		return cycle;
	}
	public void setCycle(int cycle) {
		this.cycle = cycle;
	}
	public int getSound() {
		return sound;
	}
	public void setSound(int sound) {
		this.sound = sound;
	}
	public boolean isEffective() {
		return effective;
	}
	
	public void setEffective(boolean effective) {
		this.effective = effective;
	}
	
	public void copy(Alarm a)
	{
		this.id = a.id;
		this.cycle = a.cycle;
		this.effective = a.effective;
		this.name = a.name;
		this.sound = a.sound;
		this.time = a.time;
	}
	
	public long getTriggerTime()
	{
		long hours = 0;
		switch(cycle)
		{
		case 0: hours = 0;break;		//once
		case 2: hours = 7 * 24;break;	//every week
		case 1:							//every day	
		case 3:							//working days				
		case 7: hours = 24;break;		//self define
		case 4: 						//every month
		{
			return getTriggerTimeOfMonth(this);
		}
		case 5:							//every month by yin
		{
			return getTriggerTimeOfMonth(this);
		}
		default: hours = 24;
		}
		return getTriggerTime(this, hours * 3600000L);
	}	
		
	private static long getTriggerTime(Alarm a, long interval)
	{
		long base = a.getTime();
		if(interval == 0)
			return base;
		
		Calendar c = Calendar.getInstance();
		long now = c.getTimeInMillis();
		long offset = now - base;
		long p = (long) Math.floor((double)offset / (double)interval);
		return (base + (p + 1) * interval);
	}
	
	private static long getTriggerTimeOfMonth(Alarm a)
	{
		long time = a.getTime();		
		Timer base = new Timer();
		base.init(time);
		
		Timer now = new Timer();
		now.init();
		
		base.set(Timer.YEAR, now.get(Timer.YEAR));
		base.set(Timer.MONTH, now.get(Timer.MONTH));
		
		int bday = base.get(Timer.DATE);
		int nday = now.get(Timer.DATE);
		if(bday < nday)
		{
			base.set(Timer.MONTH, base.get(Timer.MONTH) + 1);
		}
		else if(bday == nday)
		{
			if(base.getTime() < now.getTime())
				base.set(Timer.MONTH, base.get(Timer.MONTH) + 1);
		}
		
		int days = base.getDaysOfMonth();
		if(days < bday)
			return -1;
		else 
			return base.getTime();	
	}
}
